package storage;

import java.util.ArrayList;
import java.util.List;
import java.io.FileOutputStream;
import org.jdom.output.XMLOutputter;
import org.jdom.Document;
import org.jdom.Element;
import storage.beans.GridBean;
import storage.beans.CellBean;

import storage.beans.SimulationBean;

public class XmlDataStorage implements IDataStorage {

  /*
   * Writes all the necessary simulation data to an XML file.
   */
  public void saveSimulation(SimulationBean sim) throws java.io.IOException {
  	XMLOutputter writer = new XMLOutputter ();
  	Element root = new Element ("simulation");
  	Document doc = new Document (root);
  	root.setAttribute ("tilt", String.valueOf(sim.getTilt ()));
    root.setAttribute ("eccentricity", String.valueOf(sim.getEccentricity ()));
    root.setAttribute ("precision", String.valueOf(sim.getPrecision ()));
    root.setAttribute ("samplingRate", String.valueOf(sim.getSamplingRate ()));
    root.setAttribute ("temporalAccuracy", String.valueOf(sim.getTemporalAccuracy ()));
    
    Element settings = new Element ("settings");
    root.addContent (settings);
    settings.setAttribute("gridSpacing", String.valueOf (sim.getGridSpacing ()));
    settings.setAttribute("timeStep", String.valueOf (sim.getTimeStep ()));
    settings.setAttribute("startDateTime", String.valueOf (sim.getStartDateTime ()));
    settings.setAttribute("endDateTime", String.valueOf (sim.getEndDateTime ()));
    
    Element snapshots = new Element ("snapshots");
    root.addContent (snapshots);
    sim.initGridIterator();
    for (GridBean gb = sim.getNextGrid (); gb != null; ) {
      Element grid = new Element ("grid");
    	grid.setAttribute ("dateTime", String.valueOf(gb.getDateTime ()));
    	gb.initCellIterator ();
    	for (CellBean cb = gb.getNextCell (); cb != null; ) {
        Element cell = new Element ("cell");
    		cell.setAttribute ("latitude", String.valueOf(cb.getLatitude ()));
    		cell.setAttribute ("longitude", String.valueOf(cb.getLongitude ()));
    		cell.setAttribute ("temperature", String.valueOf(cb.getTemperature ()));
    		grid.addContent(cell);
    	}
    	snapshots.addContent (grid);
    }
    writer.output(doc, new FileOutputStream ("data.xml"));
  }
  
  public List getSimulations(int tilt, int eccentricity) {
    ArrayList simulations = new ArrayList();
    return simulations;
  }
}
